import Vue from 'vue/dist/vue.esm'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import {getLocal} from './localstore'

import IndexView from './views/index'
import LoginView from './views/login'

import { store } from './vux'

const router = new VueRouter({
  scrollBehavior: () => ({
    y: 0
  }),
  routes: [
    {
      path: '/index/:folder',
      name: 'Index',
      component: IndexView,
      meta: {
        path: '/index/:folder',
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'Login',
      component: LoginView
    }
  ]
})
router.beforeEach((to, from, next) => {
  let token = getLocal('token')
  // console.log(token, to)
  if (to.meta.requiresAuth) {
    if (token) {
      // store.dispatch('getUser').then(() => {
      //   next()
      // }).catch(() => {
      // //
      // })
      store.dispatch('getUser')
      next()
    } else {
      store.dispatch('logOut')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router
